﻿' ----------------------------------------------------------------------------------
' Microsoft Developer & Platform Evangelism
' 
' Copyright (c) Microsoft Corporation. All rights reserved.
' 
' THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, 
' EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES 
' OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
' ----------------------------------------------------------------------------------
' The example companies, organizations, products, domain names,
' e-mail addresses, logos, people, places, and events depicted
' herein are fictitious.  No association with any real company,
' organization, product, domain name, email address, logo, person,
' places, or events is intended or should be inferred.
' ----------------------------------------------------------------------------------

Imports Microsoft.Samples.WindowsPhoneCloud.Phone.Helpers
Imports Microsoft.Samples.WindowsPhoneCloud.Phone.ViewModel
Imports SL.Phone.Federation.Utilities
Imports System.Windows.Navigation
Imports System.IO.IsolatedStorage

Namespace Pages
    Partial Public Class LoginPage
        Inherits PhoneApplicationPage
        Private ReadOnly rstrStore As RequestSecurityTokenResponseStore = TryCast(App.Current.Resources("rstrStore"), RequestSecurityTokenResponseStore)

        Public Sub New()
            Me.InitializeComponent()
            Me.PageTransitionReset.Begin()

            AddHandler Me.SignInControl.RequestSecurityTokenResponseCompleted, Sub(s, e) Me.ViewModel.HandleRequestSecurityTokenResponseCompleted(s, e, Sub()
                                                                                                                                                            SetIsolatedStorageSetting("UserIsRegistered", True)
                                                                                                                                                            Me.NavigationService.Navigate(New Uri("/Pages/MainPage.xaml", UriKind.Relative))
                                                                                                                                                        End Sub,
                                                                                                                                                        Sub()
                                                                                                                                                            SetIsolatedStorageSetting("UserIsRegistered", False)
                                                                                                                                                            Me.NavigationService.Navigate(New Uri("/Pages/RegisterPage.xaml", UriKind.Relative))
                                                                                                                                                        End Sub,
                                                                                                                                                        Sub(errorMessage)
                                                                                                                                                            Me.SignInControl.GetSecurityToken()
                                                                                                                                                            errorMessage = If(String.IsNullOrEmpty(errorMessage), "An error occurred determining if the user was already registered. Make sure that the appropriate SSL certificate is installed.", errorMessage)
                                                                                                                                                            MessageBox.Show(errorMessage, "Registration Error", MessageBoxButton.OK)
                                                                                                                                                        End Sub)
            AddHandler Me.SignInControl.NavigatingToIdentityProvider, Sub(s, e)
                                                                          ' When the user navigates to an identity provider, the previous login information is cleaned up.
                                                                          SetIsolatedStorageSetting("UserIsRegistered", False)
                                                                          App.CloudClientFactory.CleanAuthenticationToken()
                                                                      End Sub
        End Sub

        Public Property ViewModel() As LoginPageViewModel
            Get
                Return TryCast(Me.DataContext, LoginPageViewModel)
            End Get
            Set(ByVal value As LoginPageViewModel)
                Me.DataContext = value
            End Set
        End Property

		Protected Overrides Sub OnNavigatedTo(ByVal e As NavigationEventArgs)
			If Me.rstrStore.IsValid() AndAlso GetIsolatedStorageSetting(Of Boolean)("UserIsRegistered") AndAlso (Not GetApplicationState(Of Boolean)("UserBackPress")) Then
				Me.NavigationService.Navigate(New Uri("/Pages/MainPage.xaml", UriKind.Relative))
			Else
				Me.StartTransition()

				SetApplicationState("UserBackPress", False)

				Me.SignInControl.GetSecurityToken()
			End If
		End Sub

        Protected Overrides Sub OnNavigatedFrom(ByVal e As NavigationEventArgs)
            Me.PageTransitionReset.Begin()
        End Sub

        Private Shared Function GetApplicationState(Of T)(ByVal key As String) As T
            If Not PhoneApplicationService.Current.State.ContainsKey(key) Then
                Return Nothing
            End If

            Return CType(PhoneApplicationService.Current.State(key), T)
        End Function

        Private Shared Sub SetApplicationState(ByVal key As String, ByVal value As Object)
            If PhoneApplicationService.Current.State.ContainsKey(key) Then
                PhoneApplicationService.Current.State.Remove(key)
            End If

            PhoneApplicationService.Current.State.Add(key, value)
        End Sub

        Private Shared Function GetIsolatedStorageSetting(Of T)(ByVal key As String) As T
            Dim isolatedStorage As IDictionary(Of String, Object) = IsolatedStorageSettings.ApplicationSettings
            If Not isolatedStorage.ContainsKey(key) Then
                Return Nothing
            End If

            Return CType(isolatedStorage(key), T)
        End Function

        Private Shared Sub SetIsolatedStorageSetting(ByVal key As String, ByVal value As Object)
            Dim isolatedStorage As IDictionary(Of String, Object) = IsolatedStorageSettings.ApplicationSettings
            If isolatedStorage.ContainsKey(key) Then
                isolatedStorage.Remove(key)
            End If

            isolatedStorage.Add(key, value)
        End Sub

        Private Sub StartTransition()
            Me.PageTransitionIn.Begin()
            If Me.ViewModel Is Nothing Then
                Me.ViewModel = New LoginPageViewModel()
            End If
        End Sub
    End Class
End Namespace